﻿(function () {
    var api = {};

    if (!window['console']) {
        var f = function () { };
        window.console = { info: f, debug: f, log: f, error: f, dir: f, warn: f };
    }

    api.isAbsoluteUri = function (uri) {
        var reg = /^https?:/i;
        return reg.test(uri);
    };

    api.callback = function (opt, data) {
        return api.callbackFunc(opt, 'ReturnUrl', data);
    };

    api.callbackFunc = function (opt, funcName, data) {
        if (!opt) {
            return alert('不存在options');
        }
        var retUrl = opt[funcName];
        if (!retUrl) {
            return alert('方法不存在options中');
        }
        var fromType = opt.FromType;
        if (api.isAbsoluteUri(retUrl)) {
            return api.postForm(retUrl, data);
        }
        try {
            var backFunc;
            switch (fromType) {
                case 0:/*web*/
                    backFunc = parent[retUrl];
                    if (!$.isFunction(backFunc)) {
                        return alert('请检查web父页面回调方法是否存在！');
                    }
                    return backFunc(data);
                    break;
                case 1:/*winForm*/
                    var d = window.external[retUrl](api.toJsonString(data));
                    if (d) {
                        return JSON.parse(d);
                    }
                    break;
                default:
                    return alert('未知来源');
                    break;
            }
        } catch (e) {
            var msg = '出错了：';
            msg += e.message;
            alert(msg);
            console.error(e);
        }
    };

    api.postForm = function (url, data) {
        var form = $('<form/>', { action: url, method: 'post' }).hide();
        if ($.isArray(data)) {
            data = { resultData: data };
        }
        $.each(data, function (k, v) {
            $('<input/>', { type: 'hidden', name: k, value: api.toJsonString(v) }).appendTo(form);
        });
        form.appendTo(document.body).trigger('submit');
    };

    api.toJsonString = function (data) {
        if (typeof data === 'string') {
            return data;
        }
        return JSON.stringify(data);
    };

    api.onerror = function () {
        window.onerror = function (url, msg) {
            alert('页面：' + url + '，出错：' + msg);
            console.error(arguments);
        };
    };

    window.mapCommon = api;
})();